import router from './index'

import {
  store,
  log
} from '@/common/app/index.js'

/**
 * 路由跳转前进行权限控制
 */
router.beforeEach((to, from, next) => {
  // 将当所有正在请求而未返回的请求取消，避免路由跳转后，请求中的数据又返回了
  if (window.axiosPromiseArr && window.axiosPromiseArr.length) {
    window.axiosPromiseArr.forEach((req) => {
      req.cancel();
    });
    window.axiosPromiseArr.length = 0;
    window.axiosKeyArr.length = 0;
  }
  const routers = store.getters.allRouters;
  if ((!routers || !routers.length) && to.path !== '/') {
    next({
      ...to,
      path: '/',
      replace: true
    });
    log.debug('当前路由列表为空，未完成路由加载，进入“/”根页面重新跳转页面');
  } else {
    if (to.path === '/') {
      let firstPath = window.systemConfig.FIRST_PAGE;
      log.debug('系统进入“/”根页面，跳转至配置的首页：', firstPath);
      let firstPage = routers.find((item) => {
        return item.path === firstPath;
      });
      if (!firstPage) {
        firstPath = routers[0].path;
        log.debug('配置的首页地址不在路由列表中，默认取路由列表第一个页面地址进行跳转，跳转地址为：', firstPath);
      }
      next({
        ...to,
        path: firstPath,
        replace: true
      });
    } else {
      let nextPath = to.path;
      let nextPage = routers.find((item) => {
        return item.path === nextPath;
      });
      if (!nextPage) {
        log.debug('当前跳转的页面地址不在路由列表中，将跳转至404页面，当前跳转的地址为：', nextPath);
        if (to.path === window.systemConfig.PAGE_NOT_FOUND) {
          nextPath = '/';
        } else {
          nextPath = window.systemConfig.PAGE_NOT_FOUND;
        }
        router.replace({
          path: nextPath,
          query: {
            to: to.path,
            from: from.path
          }
        });
      } else {
        next();
      }
    }
  }
});
